{extend name="common/base" /}
{block name="body"} 
<div class="Content" id="content">
    <div class="container">
        <div class="FormPage StoreModel">
            <form class="layui-form" lay-filter="shippingForm">
                <div class="form-item-inline">
                    <label class="must form-label">模板名称：</label>
                    <div class="input-inline">
                        <input type="text" name="name" placeholder="请输入模板名称" 
                               lay-verify="required|maxlength" maxlength="100" value="{$template.name |default=''}" class="layui-input">
                    </div>
                </div>
                
                <div class="form-item-inline">
                    <label class="must form-label">模板类型：</label>
                    <div class="input-inline">
                        <input type="radio" name="is_free_shipping" value="0" title="买家承担运费" {if isset($template) && $template.is_free_shipping == 0} checked {/if}>
                        <input type="radio" name="is_free_shipping" value="1" title="卖家包邮" {if isset($template) && $template.is_free_shipping == 1} checked {/if}>
                    </div>
                </div>
                
                <div class="form-item-inline">
                    <label class="must form-label">计价方式：</label>
                    <div class="input-inline">
                        <input type="radio" name="type" value="1" title="按件数" {if isset($template) && $template.type == 1} checked {/if}>
                        <input type="radio" name="type" value="2" title="按重量" {if isset($template) && $template.type == 2} checked {/if}>
                        <input type="radio" name="type" value="3" title="按体积" {if isset($template) && $template.type == 3} checked {/if}>
                    </div>
                </div>
                
                <div class="form-item-inline" style="align-items: flex-start;">
                    <label class="must form-label">配送区域及运费：</label>
                    <div class="block">
                        <div class="tab-view">
                            <table class="layui-table" lay-size="sm" lay-skin="line" id="shippingRuleTable">
                                <colgroup>
                                    <col width="300">
                                    <col width="150">
                                    <col width="150">
                                    <col width="150">
                                    <col width="150">
                                    <col width="80">
                                </colgroup>
                                <thead>
                                    <tr>
                                        <th>可配送区域</th>
                                        <th id="firstUnitTitle">首件（个）</th>
                                        <th>运费（元）</th>
                                        <th id="continueUnitTitle">续件（个）</th>
                                        <th>续费（元）</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <!-- 动态生成行 -->
                                </tbody>
                            </table>
                        </div>
                        <button type="button" class="layui-btn layui-btn-normal layui-btn-xs" id="addRegionBtn">
                            + 添加可配送区域
                        </button>
                        
                        <div style="margin-top: 20px;">
                            <input type="checkbox" name="is_default" lay-skin="primary" title="设为默认模板">
                        </div>
                    </div>
                </div>
                
                <div class="form-item-inline">
                    <label class="form-label"></label>
                    <div class="input-inline foot">
                        <button type="button" class="layui-btn btn-gary" id="cancelBtn">取消</button>
                        <button class="layui-btn" lay-submit lay-filter="submitForm">保存</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 地区选择弹窗模板 -->
<script type="text/html" id="regionTpl">
    <div class="layui-form" style="padding: 20px;">
        <div id="regionTree" style="height: 300px; overflow: auto;"></div>
    </div>
</script>
{/block}

{block name="js"} 
<script>
    changeTitleName('运费模板');
    
    layui.use(['form', 'table', 'layer', 'tree', 'util'], function(){
        var form = layui.form;
        var table = layui.table;
        var layer = layui.layer;
        var tree = layui.tree;
        var util = layui.util;
        var $ = layui.$;
        
        // 根据计价方式更新表头
        function updateUnitTitle(type) {
            var firstTitle = '首件（个）';
            var continueTitle = '续件（个）';
            
            if(type == 2) {
                firstTitle = '首重（kg）';
                continueTitle = '续重（kg）';
            } else if(type == 3) {
                firstTitle = '首体积（m³）';
                continueTitle = '续体积（m³）';
            }
            
            $('#firstUnitTitle').text(firstTitle);
            $('#continueUnitTitle').text(continueTitle);
        }
        
        // 初始化计价方式表头
        updateUnitTitle(1);
        
        // 监听计价方式变化
        form.on('radio(type)', function(data){
            updateUnitTitle(data.value);
        });
        
        // 添加地区行
        $('#addRegionBtn').on('click', function(){
            addRegionRow();
        });
        
        // 删除行
        $(document).on('click', '.delete-row', function(){
            $(this).closest('tr').remove();
        });
        
        // 编辑地区
        $(document).on('click', '.edit-region', function(){
            var tr = $(this).closest('tr');
            var regionNames = tr.data('region-names') || '';
            var regionIds = tr.data('region-ids') || '';
            
            var index = layer.open({
                type: 1,
                title: '选择配送区域',
                content: $('#regionTpl').html(),
                area: ['400px', '500px'],
                btn: ['确定', '取消'],
                success: function(layero, index){
                    // 加载地区树形数据
                    $.ajax({
                        url: '/merchant/get_region_data',
                        type: 'GET',
                        success: function(res){
                            if(res.code == 0){
                                // 初始化树形组件
                                tree.render({
                                    elem: '#regionTree',
                                    data: res.data,
                                    id: 'regionTree',
                                    showCheckbox: true,
                                    oncheck: function(obj){
                                        console.log(obj.data); // 得到当前点击的节点数据
                                    }
                                });
                                
                                // 如果有已选地区，设置选中状态
                                if(regionIds){
                                    var ids = regionIds.split(',');
                                    tree.setChecked('regionTree', ids);
                                }
                            }
                        }
                    });
                },
                yes: function(index, layero){
                    var checkedData = tree.getChecked('regionTree');
                    var regionNames = [];
                    var regionIds = [];
                    
                    checkedData.forEach(function(item){
                        regionNames.push(item.title);
                        regionIds.push(item.id);
                        if(item.children){
                            item.children.forEach(function(child){
                                regionNames.push(child.title);
                                regionIds.push(child.id);
                            });
                        }
                    });
                    
                    if(regionNames.length === 0){
                        layer.msg('请至少选择一个地区', {icon: 2});
                        return false;
                    }
                    
                    // 更新行数据
                    tr.find('.region-names').text(regionNames.join(','));
                    tr.data('region-names', regionNames.join(','));
                    tr.data('region-ids', regionIds.join(','));
                    layer.close(index);
                }
            });
        });
        
        // 添加新的地区行
        function addRegionRow(){
            var html = '<tr>' +
                '<td class="region-names">选择地区 <i class="layui-icon layui-icon-edit edit-region"></i></td>' +
                '<td><input type="number" name="first_unit" class="layui-input" lay-verify="required|number" min="0" step="0.01" value="1"></td>' +
                '<td><input type="number" name="first_price" class="layui-input" lay-verify="required|number" min="0" step="0.01" value="0"></td>' +
                '<td><input type="number" name="continue_unit" class="layui-input" lay-verify="required|number" min="0" step="0.01" value="1"></td>' +
                '<td><input type="number" name="continue_price" class="layui-input" lay-verify="required|number" min="0" step="0.01" value="0"></td>' +
                '<td><a class="delete-row" style="color: #FF5722;">删除</a></td>' +
            '</tr>';
            
            $('#shippingRuleTable tbody').append(html);
        }
        
        // 表单提交
        form.on('submit(submitForm)', function(data){
            var formData = data.field;
            var rules = [];
            
            // 验证是否有配送规则
            if($('#shippingRuleTable tbody tr').length === 0){
                layer.msg('请至少添加一个配送区域', {icon: 2});
                return false;
            }
            
            // 收集配送规则
            $('#shippingRuleTable tbody tr').each(function(){
                var $tr = $(this);
                var regionIds = $tr.data('region-ids');
                var regionNames = $tr.data('region-names');
                
                if(!regionIds){
                    layer.msg('请为所有配送区域选择具体地区', {icon: 2});
                    return false;
                }
                
                rules.push({
                    region_ids: regionIds,
                    region_names: regionNames,
                    first_unit: $tr.find('input[name="first_unit"]').val(),
                    first_price: $tr.find('input[name="first_price"]').val(),
                    continue_unit: $tr.find('input[name="continue_unit"]').val(),
                    continue_price: $tr.find('input[name="continue_price"]').val()
                });
            });
            
            if(rules.length === 0) return false;
            
            formData.rules = rules;
            
            // 提交数据
            var loading = layer.load(2);
            $.ajax({
                url: '/merchant/shipping_template_save',
                type: 'POST',
                data: formData,
                dataType: 'json',
                success: function(res){
                    layer.close(loading);
                    if(res.code === 200){
                        layer.msg('保存成功', {icon: 1});
                        window.location.reload();
                        // setTimeout(function(){
                        //     location.href = '/shipping_template/index';
                        // }, 1500);
                    }else{
                        layer.msg(res.msg || '保存失败', {icon: 2});
                    }
                },
                error: function(){
                    layer.close(loading);
                    layer.msg('网络错误，请稍后再试', {icon: 2});
                }
            });
            
            return false;
        });
        
        // 取消按钮
        $('#cancelBtn').on('click', function(){
            location.href = '/shipping_template/index';
        });
        
        // 如果是编辑页面，初始化数据
        {if isset($template)}
            // 填充基本数据
            form.val('shippingForm', {
                "name": "{$template.name}",
                "type": "{$template.type}",
                "is_free_shipping": "{$template.is_free_shipping}",
                "is_default": "{$template.is_default|default=0}"
            });
            
            // 更新表头
            updateUnitTitle({$template.type});
            
            // 填充规则数据
            {if !empty($template.rules)}
                {foreach $template.rules as $rule}
                    addRegionRow();
                    var $tr = $('#shippingRuleTable tbody tr:last');
                    $tr.find('.region-names').text('{$rule.region_names}');
                    $tr.data('region-names', '{$rule.region_names}');
                    $tr.data('region-ids', '{$rule.region_ids}');
                    $tr.find('input[name="first_unit"]').val('{$rule.first_unit}');
                    $tr.find('input[name="first_price"]').val('{$rule.first_price}');
                    $tr.find('input[name="continue_unit"]').val('{$rule.continue_unit}');
                    $tr.find('input[name="continue_price"]').val('{$rule.continue_price}');
                {/foreach}
            {/if}
        {/if}
    });
</script>
{/block}